from datetime import datetime
from SessionWrapper import sessionwrapper
from dbmanager.sqllite import DBProcesstime
from processutil import ProcessIsExit
import requests
from dbmanager.sqllite import SqliteSession
import logging

LOGGER = logging.getLogger(__name__)


class ProcessDBStore(object):
    '''
     查询进程是否存在，并存储数据库

    '''

    def __init__(self, name, isreport, **kwargs):
        '''
        :param name: processname
        :param isreport: 是否报告server端
        :param url: 是否报告server端
        '''
        self.isreport = isreport
        self.name = name
        if isreport:
            self.url = kwargs.get('url', '')

    @sessionwrapper(SqliteSession)
    def scheduled(self, session):
        '''
         定时任务执行方法
        :return:
        '''
        LOGGER.info("process scheduled")
        flag = ProcessIsExit(self.name)
        date = datetime.now()
        obj = None
        if flag:
            obj = DBProcesstime(name=self.name, isOpen=True, date=date)
            LOGGER.info("process  is open")
        else:
            LOGGER.info("process  is open")
            obj = DBProcesstime(name=self.name, isOpen=False, date=date)
            if self.isreport:
                try:
                    requests.get(self.url, timeout=10)
                except requests.exceptions.ConnectionError as e:
                    LOGGER.error("process request timeout")
        session.add(obj)
